package managers.messengerManager;

import java.net.InetAddress;
import java.util.Hashtable;

import managers.conversationManager.ConversationManager;
import managers.messengerManager.services.Service;
import utils.ManagingMessage;
import utils.ManagingMessage.Type;
import utils.StackTracePrinter;
import utils.UserData;
import utils.UserState;

public class ManagePacketRunnable implements Runnable {

	private MessengerManager manager = MessengerManager.getSharedInstance();
	private ManagingMessage managingMessage;


	public ManagePacketRunnable(ManagingMessage managingMessage) {
		this.managingMessage = managingMessage;
	}


	@Override
	public void run() {
		try {
			managePacket();
		} catch (Exception e) {
			// do nothing
			StackTracePrinter.print(e);
		}		
	}


	private void managePacket() throws Exception {

		manager.setRecentFeedbackFromServer(true);
		switch (managingMessage.getType()) {


		case LIFE_TEST_REQUEST:
			System.out.println("Received life test request from server.");
			//server is asking for this client is still connected or not.
			ManagingMessage ack = new ManagingMessage(Type.LIFE_TEST_ACK);
			ack.putProperty("userId", MessengerManager.getSharedInstance().getUserId());
			manager.getSingleProtocol().send(ack, (InetAddress) managingMessage.getProperty("senderIpAddress"), (Integer) managingMessage.getProperty("senderPort"));
			System.out.println("Sent life test ack to server.");
			break;
		case CHANGE_STATE_ACK:
			Service changeStateService = manager.getService("Change State");
			changeStateService.wakeUp(managingMessage.getProperty("state"));
			System.out.println("Received state change ack");
			break;
		case USER_DATA_ACK:
			ConversationManager.getSharedInstance().getUserRequestsManager().ackUserDataRequest((UserData) managingMessage.getProperty("userData"));
			System.out.println("Received user data");
			break;
		case LOGIN_ACK:
			manager.getService("Connection").wakeUp(true);
			manager.getUsersManager().updateUsers((Hashtable<Integer, UserState>) managingMessage.getProperty("onlineUsers"), true);
			System.out.println("UPDATE FROM SINGLE");
			break;
		case SUPPORT_DOCUMENT_ACK:
			manager.getService("sendSupportDocument").wakeUp(true);
		}

	}

}
